<?php

namespace app\admin\model\yxerp;

use think\Model;

class AiAttachment extends Model
{
    // 表名
    protected $name = 'yxerp_ai_attachments';
    
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    
    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    
    // 追加属性
    protected $append = [
        'processing_result_array',
        'create_time_text'
    ];
    
    // 设置处理结果
    public function setProcessingResultAttr($value)
    {
        if (is_array($value)) {
            return json_encode($value);
        }
        return $value;
    }
    
    // 获取处理结果数组
    public function getProcessingResultArrayAttr($value, $data)
    {
        $result = isset($data['processing_result']) ? $data['processing_result'] : '';
        return json_decode($result, true) ?: [];
    }
    
    // 格式化创建时间
    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ?: $data['create_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }
    
    // 所属消息
    public function message()
    {
        return $this->belongsTo('app\admin\model\yxerp\AiMessage', 'message_id', 'id');
    }
    
    // 所属会话
    public function conversation()
    {
        return $this->belongsTo('app\admin\model\yxerp\AiConversation', 'conversation_id', 'id');
    }
    
    // 上传附件
    public static function uploadAttachment($file, $conversationId, $messageId = null)
    {
        $info = $file->validate(['size' => 1024 * 1024 * 20, 'ext' => 'jpg,jpeg,png,gif,pdf,doc,docx,xls,xlsx,txt'])->move('uploads/aichat');
        
        if (!$info) {
            return false;
        }
        
        $savename = str_replace('\\', '/', $info->getSaveName());
        
        $attachment = new self;
        $attachment->conversation_id = $conversationId;
        $attachment->message_id = $messageId;
        $attachment->filename = $info->getInfo('name');
        $attachment->path = 'uploads/aichat/' . $savename;
        $attachment->url = '/uploads/aichat/' . $savename;
        $attachment->mime_type = $info->getInfo('type');
        $attachment->size = $info->getInfo('size');
        $attachment->processed = 0;
        $attachment->save();
        
        return $attachment;
    }
    
    // 将附件关联到消息
    public function linkToMessage($messageId)
    {
        $this->message_id = $messageId;
        $this->save();
        
        return $this;
    }
    
    // 标记为已处理
    public function markAsProcessed($result = [])
    {
        $this->processed = 1;
        if (!empty($result)) {
            $this->processing_result = $result;
        }
        $this->save();
        
        return $this;
    }
    
    // 删除文件
    public function deleteFile()
    {
        if (file_exists(public_path() . $this->path)) {
            @unlink(public_path() . $this->path);
        }
        
        return true;
    }
    
    // 获取会话的所有附件
    public static function getConversationAttachments($conversationId)
    {
        return self::where('conversation_id', $conversationId)
            ->order('id', 'DESC')
            ->select();
    }
} 